#include "GlobalManager.h"

GlobalManager::GlobalManager()
{
	//ctor
	m_DataMap.clear();
	m_pDB = nullptr;
}

GlobalManager::~GlobalManager()
{
	//dtor
	m_pDB = nullptr;
}

bool GlobalManager::Init(Database& _pDB)
{
	m_pDB = &_pDB;

	map<int, tGlobal> DbDataMap = m_pDB->GetGlobalMap();

	map<int, tGlobal>::iterator iter;
	for(iter = DbDataMap.begin(); iter != DbDataMap.end(); iter++)
	{
		eGlobalKey key = (eGlobalKey)iter->first;
		if(this->m_DataMap.count(key)!= 0)
		{
			Debug::Warn("GlobalManager::Init error,  _key repeated: ", (int)key);
			continue;
		}

		m_DataMap[key] = iter->second.value;
		Debug::Log("GlobalManager::Init key/value: ", (int)key, "/", m_DataMap[key]);
	}

	return true;
}

int GlobalManager::GetValue(eGlobalKey _key)
{
	if(m_DataMap.count(_key)== 0)
	{
		Debug::Warn("GlobalManager::GetValue not found. will create. _key: ", (int)_key);
		m_DataMap[_key] = 0;
	}

	Debug::Log(__func__, " will return:", m_DataMap[_key]);
	return m_DataMap[_key];
}

bool GlobalManager::UpdateValue(eGlobalKey _key, int _value)
{
//	if(m_DataMap.count(_key)== 0)
//	{
//		Debug::Error("GlobalManager::UpdateValue error, _key: ", (int)_key);
//		return false;
//	}

Debug::Log("==>> GlobalManager::UpdateValue, key:", (int)_key, " value:", _value);

	tGlobal Global1;
	Global1.id = (int) _key;
	Global1.key = (int) _key;
	Global1.value = _value;
	if(! m_pDB->UpdateGlobal(Global1))
	{
		Debug::Error("GlobalManager::UpdateValue error, _key: ", (int)_key, " value:", _value);
		return false;
	}

	m_DataMap[_key] = _value;

	Debug::Log("==>> UpdateValue ret ture, key:", (int)_key, " value:", m_DataMap[_key]);
	return true;
}
